<?php

/**
 * @author      :   nghialh
 * @name        :   My_Plugin_Auth
 * @version     :   201104
 * @copyright   :   My company
 * @todo        :   Acl plugin
 */
class My_Plugin_Auth extends Zend_Controller_Plugin_Abstract {

    public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request) {
        if ((($request->getControllerName() == 'foconnect') && ($request->getActionName() == 'check-login'))
                || ($request->getControllerName() == 'widget')
                || (($request->getModuleName() == 'frontend') && ($request->getControllerName() == 'comment') && ( ($request->getActionName() == 'index') || ($request->getActionName() == 'paging')))) {
            return;
        }
        $auth = Zend_Auth::getInstance();
        if (!$auth->hasIdentity()) {
            $result = $auth->authenticate(new My_BBAuthenticate());

            if ($result->getCode() == Zend_Auth_Result::FAILURE_IDENTITY_AMBIGUOUS) {
                session_destroy();
                if (isset($_SERVER['HTTP_COOKIE'])) {
                    $cookies = explode(';', $_SERVER['HTTP_COOKIE']);
                    foreach ($cookies as $cookie) {
                        $parts = explode('=', $cookie);
                        $name = trim($parts[0]);
                        setcookie($name, '', time() - 1000);
                        setcookie($name, '', time() - 1000, '/');
                    }
                }
                //FAILURE_IDENTITY_AMBIGUOUS
//                return $request->setModuleName('frontend')->setControllerName('foconnect')->setActionName('logout');
                // redirect to account confirm
                $redirect = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
                $redirect->gotoUrl('http://id.fpt.net/xac-nhan-tai-khoan.html?referersp=' . $request->getScheme() . '://' . $request->getHttpHost() . $request->getRequestUri())->redirectAndExit();
            }
        }

        if ($auth->hasIdentity()) {
            $instanceServiceFospApi = ServiceFospApi::getInstance();
//            $instanceServiceFospApi->checkToken();
//            if (empty($_REQUEST['code'])) {
//                $user = $instanceServiceFospApi->getUserInfo();
//                if (empty($_COOKIE['fospconnect']) && !empty($user)) {
//                    // cookie timeout but not connection
//                    return $request->setModuleName('frontend')->setControllerName('foconnect')->setActionName('logout');
//                }
//            }

            $identity = $auth->getIdentity();
            define(FPTID, (int) $identity['fpt_id']);
            define(USERNAME, $identity['username']);
            define(FULLNAME, $identity['full_name']);
            define(AVATAR, $identity['avatar']);
            define(UID, $identity['user_id']);
            define(GID, $identity['group_id']);
        }
    }

}